<template>
  <Spin :spinning="loading" tip="Loading...">
  <div>
    <!-- table -->
    <!-- 紧急返件要求下发 - 新增 -->
    <BreakSpace label="质量信息" :containerStyle="{ marginBottom: '10px' }"/>
    <FormPanel ref="formPanel1" :list="formList" :cols="3" :formType="'add'" labelWidth="110" :isSubmitBtn="false"
               @formChange="formChangeHandle"/>
    <div style="margin-bottom: 1rem;"></div>
    <BreakSpace label="紧急返件列表" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
      ref="table"
      :columns="columns"
      :params="fetchParams"
      :dataSource="dataList"
      :datakey="'items'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectChange"
      :isSelectColumn="false"
      :isPagination = false
      height="auto"
    > <template slot="controls" slot-scope="props">
      <multiuse-button size="small" type="primary" icon="el-icon-plus" :click="downloadTemplate.bind()">下载模板</multiuse-button>
      <multiuse-button size="small" type="primary" icon="el-icon-upload" @click="showImportFun()">导入</multiuse-button>
      <multiuse-button size="small" type="primary" icon="el-icon-plus" :click="addTurnOn.bind()">新增</multiuse-button>
    </template></FilterTable>
    <div style="margin-bottom: 1rem;"></div>
    <FormPanel ref="formPanel2" :list="formList2" :cols="3" :formType="'add'" labelWidth="100" :isSubmitBtn="false"
               @formChange="form2ChangeHandle"/>
    <div style="margin-bottom: 3rem;"></div>
    <div
      :style="{
        position: 'fixed',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <multiuse-button type="primary" :click="submit.bind()">拆分下发</multiuse-button>
      <multiuse-button type="primary" :click="saveDialog.bind()">保存</multiuse-button>
      <multiuse-button type="primary" @click="closeDialog">关 闭</multiuse-button>
    </div>
    <BaseDialog :visible.sync="quality" :title="'质量报告选择'" destroyOnClose width="850px" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <quality @close="close" @save="saveQuality"></quality>
    </BaseDialog>
    <BaseDialog :visible.sync="zhusunjian" :title="'主损件选择'" destroyOnClose :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <Selectzhusunjian @close="zhusunjianClose" @save="zhusunjianSave"></Selectzhusunjian>
    </BaseDialog>
    <BaseDialog :visible.sync="showImport" title="导入" icon="el-icon-upload" width="800px" destroyOnClose :containerStyle="{ height: '100%', overflow: 'auto'  }">
      <importOrderParameterModel @importclose="save" @close="closeImport"/>
    </BaseDialog>
    <BaseDialog :visible.sync="application" :title="'索赔单选择'" destroyOnClose :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <SelectClaimApplication @close="applicationClose" @save="applicationSave"></SelectClaimApplication>
    </BaseDialog>
    <BaseDialog :visible.sync="visibleRe" :title="'收件信息选择'" destroyOnClose width="850px" :containerStyle="{height: 'calc(70% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <Recevier @close="closeRe" @save="saveRe"></Recevier>
    </BaseDialog>
    <div style="margin-bottom: 1rem;"></div>
  </div>
  </Spin>
</template>
<script>
  import quality from './qualityNoQuery.vue';
  import { getPartType } from '@/api/dictionary/index';
  import Selectzhusunjian from '@/pages/claimDemage/tools/vehicle.vue';
  import {editSave,downloadModel,quyUrgent,splitByPtId} from '@/api/claim/factory/QualityInformationManagement_OEM/CoreIssueRules';
  import { exportExcelFile } from '@/utils/index';
  import { isFormEmpty } from '@/utils/index';
  import importOrderParameterModel from './importOrderParameterModel.vue';
  import moment from "moment";
  import { dictionary } from '@/utils/dictMixin';
  import SelectClaimApplication from "./SelectClaimApplication";
  import { quySP}  from '@/api/claim/dealer/ClaimApplication/index';
  import Recevier from "./ModelVehicle";
  export default {
    props: ['type', 'rowData'],
    mixins: [dictionary],
    components: {
      quality,Selectzhusunjian,importOrderParameterModel,SelectClaimApplication,Recevier

    },
    data() {
      return {
        loading: false,
        dataList: [],
        collapse: false,
        infoId: null,
        // topFilterInit: this.topFilterInitFun(),
        // fetchApi: getUser,
        fetchParams: {}, //ipa 接口
        selectedRows: [], //选中经销商
        columns: this.creatHeader(),
        formList: this.createFormList(),
        formList2: this.createFormList2(),
        saveData: null,
        saveData1:null,
        quality:false,
        zhusunjian:false,
        showImport:false,
        application:false,
        visibleRe:false
      };
    },
    async created() {
      this.loading = true;
      await this.chuqi();
      await this.getList(this.rowData.urgentId);
      this.loading = false;
    },
    methods: {
      async chuqi() {
        // console.log("进来了")
        // const res1 = await getPartType({type: 5564});
        // if (res1.resultCode == 200) {
        //   this.formList.find(x => x.fieldName == 'dataSource').itemList = res1.data.map(y => ({
        //     text: y.codeCnDesc,
        //     value: y.codeId
        //   }));
        // }
        // const res2 = await getPartType({type: 5565});
        // if (res1.resultCode == 200) {
        //   this.formList.find(x => x.fieldName == 'urgentStatus').itemList = res2.data.map(y => ({
        //     text: y.codeCnDesc,
        //     value: y.codeId
        //   }));
        // }
        // const res5 = await getPartType( {type:5500});
        // if (res5.resultCode == 200) {
        //   this.formList.find(x => x.fieldName == 'isKeep').itemList = res5.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
        // }
      },
      //提交
      async submit() {
        this.$refs.formPanel1.SUBMIT_FORM();
        this.$refs.formPanel2.SUBMIT_FORM();
        this.saveData = Object.assign(this.saveData, this.saveData1);

        let arr2 = [];
        this.$refs.table.$refs.pageTable.list.map(x => {
          delete  x.dtlId;
          arr2.push(x);
        });
        this.saveData.dtlList = arr2;
        this.saveData.reportId = this.reportId;
        this.saveData.cmsClaimId = this.cmsClaimId;
        this.saveData.delDtlIds = this.partIds;
        this.saveData.urgentId = this.rowData.urgentId;
        this.saveData.ownerCode = this.rowData.ownerCode;
        this.saveData.isDeleted = this.rowData.isDeleted;
        this.saveData.urgentStatus = 55651003;
        let tableList = this.$refs.table.$refs.pageTable.list;
        tableList.map((x) => {

          let istable = this.$refs.table.$refs.pageTable.GET_REQUIRED_ERROR();
          if (istable) {
            this.number = 1;
          } else {
            this.number = 2;
          }
        })
        if (this.saveData && this.number==2 &&this.saveData1) {
          this.loading = true;
          let res = await splitByPtId(this.saveData);
          if (res.resultCode === 200) {
            this.$emit('save');
            return this.$notify.success({ title: '提示信息', message: '保存成功' });
          } else {
            this.loading = false;
            this.$notify.error({ title: '提示信息', message: res.errMsg || '保存失败!' });
            this.closeDialog();
          }
        }
      },
      async getList(id) {
        let res = await quyUrgent({ id: id });
        let data = res.data;
        //临时属性
        this.partId = data.partId; //主损件id
        this.modelId = data.modelId; //车型id
        this.modelCode = data.modelCode; //车型Code
        this.reportId = data.reportId; //故障现象主键
        this.cmsClaimId = data.cmsClaimId;
        if(data.saleDate){
          data.saleDate = moment(data.saleDate).format('YYYY-MM-DD');
        }
        if(data.prodDate){
          data.prodDate = moment(data.prodDate).format('YYYY-MM-DD');
        }
        //为2个form赋值
        for (let i in data) {
          this.formList.map(y => {
            if (i == y.fieldName) {
              y.initialValue = data[i];
            }
          });
        }

        for (let i in data) {
          this.formList2.map(y => {
            if (i == y.fieldName) {
              y.initialValue = data[i];
            }
          });
        }
        //为table赋值

        let records2 = data.dtlList;
        if (isFormEmpty(records2)) {
          records2 = [];
        }
        let partIds = [];
        this.$refs.table.$refs.pageTable.EXECUTE_INSERT(records2);
        this.$refs.table.$refs.pageTable.list.map(x => {
          partIds.push(x.dtlId);
        });
        let ids = '';
        partIds.map(x => {
          ids += x + ','
        });
        this.partIds = ids;
        console.info(res);
        this.newVar = data;
      },
      save(val) {
        this.showImport = false;
        this.$refs.table.$refs.pageTable.EXECUTE_INSERT(val);
      },
      closeImport(){
        this.showImport = false;
      },
      showImportFun() {
        this.showImport = true;
      },
      //下载模板
      downloadTemplate() {
        this.$confirm('此操作将下载excel模板, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.exportLoading = true;
          downloadModel().then(res => {
            exportExcelFile(res.data, '紧急返件要求下发导入模板');
            this.exportLoading = false;
          });
        });
      },
      qualityNo() {
        this.quality = true;
      },
      formChangeHandle(val) {
        console.log(val);
        this.saveData = val;
      },
      form2ChangeHandle(val) {
        console.log(val);
        this.saveData1 = val;
      },
      //搜索获取数据
      changeHandle(val) {
        this.fetchParams = val;
        console.log(val);
      },
      //选中
      selectChange(rows) {
        this.selectedRows = rows;
        console.log(this.selectedRows);
      },
      closeRe() {
        this.visibleRe = false;
      },
      saveRe(val) {
        this.visibleRe = false;
        this.$refs.table.$refs.pageTable.list.map(x => {
          console.log(x.index);
          console.log(this.index);
          if(x.index==this.index){
            x.receiver= val[0].receiver;
            x.receiverTel= val[0].receiverTel;
            x.receiverAddress= val[0].receiverAddress;
          }
        });
        // this.columns.find(item => item.dataIndex === 'receiver'). = obj[0].receiver
      },
      openDescDialog(val){
        this.visibleRe = true;
        this.index=val.index;
      },
      //保存
      async saveDialog() {
        this.$refs.formPanel1.SUBMIT_FORM();
        this.$refs.formPanel2.SUBMIT_FORM();
        this.saveData = Object.assign(this.saveData, this.saveData1);

        let arr2 = [];
        this.$refs.table.$refs.pageTable.list.map(x => {
          delete  x.dtlId;
          arr2.push(x);
        });
        this.saveData.dtlList = arr2;
        this.saveData.reportId = this.reportId==null?null:this.reportId;
        this.saveData.cmsClaimId = this.cmsClaimId;
        this.saveData.delDtlIds = this.partIds;
        this.saveData.urgentId = this.rowData.urgentId;
        this.saveData.ownerCode = this.rowData.ownerCode;
        this.saveData.isDeleted = this.rowData.isDeleted;
        this.saveData.urgentStatus = 55651001;
          let tableList = this.$refs.table.$refs.pageTable.list;
          tableList.map((x) => {

            let istable = this.$refs.table.$refs.pageTable.GET_REQUIRED_ERROR();
            if (istable) {
              this.number = 1;
            } else {
              this.number = 2;
            }
          })
        if (this.saveData && this.number==2 &&this.saveData1) {
          this.loading = true;
          let res = await editSave(this.saveData);
          if (res.resultCode === 200) {
            this.closeDialog('refresh');
            return this.$notify.success({ title: '提示信息', message: '保存成功' });
            this.$emit('save');
          } else {
            this.loading = false;
            this.$notify.error({ title: '提示信息', message: res.errMsg || '保存失败!' });
            this.closeDialog();
          }
        }
      },
      zhusunjianSave(obj) {
        var list = [];
        list = this.$refs.table.$refs.pageTable.list;
        if(list.length>0){
          obj[0].receiver = list[0].receiver;
          obj[0].receiverTel = list[0].receiverTel;
          obj[0].receiverAddress = list[0].receiverAddress;
        }
        this.$refs.table.$refs.pageTable.EXECUTE_INSERT(obj);
        this.zhusunjian = false;
      },
      //主损件
      zhusunjianClose() {
        this.zhusunjian = false;
      },
      //取消操作
      closeDialog() {
        this.$emit('close', {visible: false, data: this.selectedRows, type: 'close'});
      },
      addTurnOn(){
        this.zhusunjian = true;
      },
      close(){
        this.quality = false;
      },
      saveQuality(obj) {
        this.formList.find(x => x.fieldName == 'reportNo').initialValue = obj[0].reportNo;
        this.formList.find(x => x.fieldName == 'dealerCode').initialValue = obj[0].ownerCode;
        this.formList.find(x => x.fieldName == 'dealerName').initialValue = obj[0].dealerName;
        this.formList.find(x => x.fieldName == 'roNo').initialValue = obj[0].roNo;
        this.formList.find(x => x.fieldName == 'vin').initialValue = obj[0].vin;
        this.formList.find(x => x.fieldName == 'cmsClaimNo').initialValue = obj[0].cmsClaimNo;
        this.formList.find(x => x.fieldName == 'prodDate').initialValue = obj[0].prodDate!=null?moment(obj[0].prodDate).format('YYYY-MM-DD'):null;
        this.formList.find(x => x.fieldName == 'saleDate').initialValue = obj[0].saleDate!=null?moment(obj[0].saleDate).format('YYYY-MM-DD'):null;
        this.formList.find(x => x.fieldName == 'driveMile').initialValue = obj[0].driveMile;
        this.formList.find(x => x.fieldName == 'serviceBeginDate').initialValue = obj[0].serviceBeginDate;
        this.formList.find(x => x.fieldName == 'partCode').initialValue = obj[0].partCode;
        this.formList.find(x => x.fieldName == 'partName').initialValue = obj[0].partName;
        this.formList.find(x => x.fieldName == 'serviceEndDate').initialValue = obj[0].serviceEndDate;
        this.formList.find(x => x.fieldName == 'faultCode').initialValue = obj[0].faultCode;
        this.formList.find(x => x.fieldName == 'faultName').initialValue = obj[0].faultName;
        this.formList.find(x => x.fieldName == 'modelName').initialValue = obj[0].modelName;
        this.formList.find(x => x.fieldName == 'isKeep').initialValue = obj[0].isKeep;
        this.formList.find(x => x.fieldName == 'keepCar').initialValue = obj[0].keepCar;
        this.cmsClaimId = obj[0].cmsClaimId;
        this.reportId = obj[0].reportId;
        this.quality = false;
      },
      delsFunXj(data) {
        this.$refs.table.$refs.pageTable.EXECUTE_DELETE([data]);
      },
      selectApplicationCode(){
        this.application = true;
      },
      applicationSave(obj){
        this.formList.find(x => x.fieldName == 'cmsClaimNo').initialValue = obj[0].claimNo;
        this.formList.find(x => x.fieldName == 'dealerName').initialValue = obj[0].ownerName;
        this.cmsClaimId = obj[0].claimId;
        this.getAuthListByauthNo(this.cmsClaimId);
        this.application = false;
      },
      async getAuthListByauthNo(id) {
        let res = await quySP({ id: id });
        let data = res.data;
        this.formList.find(x => x.fieldName == 'reportNo').initialValue ="";
        this.formList.find(x => x.fieldName == 'dealerCode').initialValue = data.ownerCode;
        this.formList.find(x => x.fieldName == 'partCode').initialValue = data.partCode;
        this.formList.find(x => x.fieldName == 'partName').initialValue = data.partName;
        this.formList.find(x => x.fieldName == 'roNo').initialValue = data.roNo;
        this.formList.find(x => x.fieldName == 'vin').initialValue = data.vin;
        this.formList.find(x => x.fieldName == 'serviceBeginDate').initialValue = data.serviceBeginDate;
        this.formList.find(x => x.fieldName == 'serviceEndDate').initialValue = data.serviceEndDate;
        this.formList.find(x => x.fieldName == 'prodDate').initialValue = data.prodDate!=null?moment(data.prodDate).format('YYYY-MM-DD'):null;
        this.formList.find(x => x.fieldName == 'saleDate').initialValue = data.saleDate!=null?moment(data.saleDate).format('YYYY-MM-DD'):null;
        this.formList.find(x => x.fieldName == 'modelName').initialValue = data.modelName;
        this.formList.find(x => x.fieldName == 'faultCode').initialValue =data.faultCode;
        this.formList.find(x => x.fieldName == 'faultName').initialValue =data.faultName;
        this.formList.find(x => x.fieldName == 'driveMile').initialValue = data.driveMile;
        this.formList.find(x => x.fieldName == 'isKeep').initialValue = "";
        this.formList.find(x => x.fieldName == 'keepCar').initialValue = "";
        this.cmsClaimId = data.claimId;
        this.faultId = data.faId;
        this.reportId = null;
        let records2 = data.partList;
        if (isFormEmpty(records2)) {
          records2 = [];
        }
        this.$refs.table.$refs.pageTable.EXECUTE_DELETE(this.$refs.table.$refs.pageTable.list);
        this.$refs.table.$refs.pageTable.EXECUTE_INSERT(records2);
      },
      applicationClose(){
        this.application = false;
      },
      //基本信息
      createFormList() {
        return [
          {
            type: 'INPUT',
            label: '紧急返件单号',
            fieldName: 'urgentNo',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '质量报告单号',
            fieldName: 'reportNo',
            readonly: true,// 只读
            // rules: [{required: true, message: '请输入质量报告单号', trigger: 'blur'}],
            unitRender: p => {
              return (
                <div>
                <multiuse-button icon="el-icon-search" onClick={() => this.qualityNo()}/>
              </div>
            );
            }
          },
          {
            type: 'SELECT',
            label: '数据来源',
            fieldName: 'dataSource',
            readonly: true,// 只读
            disabled: true, // 置会
            itemList: this.createDictList('5564'),
          },
          {
            type: 'INPUT',
            label: '经销商代码',
            fieldName: 'dealerCode',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '经销商名称',
            fieldName: 'dealerName',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'SELECT',
            label: '紧急返件单状态',
            fieldName: 'urgentStatus',
            readonly: true,// 只读
            disabled: true, // 置会
            itemList: this.createDictList('5565'),
          },
          {
            type: 'INPUT',
            label: '维修工单号',
            fieldName: 'roNo',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: 'VIN',
            fieldName: 'vin',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '索赔单号',
            fieldName: 'cmsClaimNo',
            readonly: true,// 只读
            // disabled: true, // 置会
            unitRender: p => {
              return (
                <div>
                  <multiuse-button icon="el-icon-search" onClick={() => this.selectApplicationCode()} />
                </div>
              );
            }
          },
          {
            type: 'INPUT',
            label: '生产日期',
            fieldName: 'prodDate',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '销售日期',
            fieldName: 'saleDate',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '行驶里程',
            fieldName: 'driveMile',
            readonly: true,// 只读
            disabled: true // 置会
          }, {
            type: 'INPUT',
            label: '维修开始时间',
            fieldName: 'serviceBeginDate',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '主损件',
            fieldName: 'partCode',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '主损件名称',
            fieldName: 'partName',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '维修结束时间',
            fieldName: 'serviceEndDate',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '故障现象代码',
            fieldName: 'faultCode',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '故障现象描述',
            fieldName: 'faultName',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'INPUT',
            label: '车型名称',
            fieldName: 'modelName',
            readonly: true,// 只读
            disabled: true // 置会
          },
          {
            type: 'SELECT',
            label: '是否留车',
            fieldName: 'isKeep',
            placeholder: '请输入...',
            disabled:true,
            itemList: this.createDictList('5500'),
          },
          {
            type: 'INPUT',
            label: '留车单号',
            fieldName: 'keepCar',
            placeholder: '请输入数量...',
            disabled: true, // 置会
          },
        ];
      },
      creatHeader() {
        return [
          {
            title: '序号',
            dataIndex: 'index',
            width: 60,
            sorter: true,
            render: props => {
              return <span>{props.row.index + 1}</span>;
            }
          },
          {
            title: '操作',
            dataIndex: 'column-action',
            width: 60,
            fixed: 'left',
            render: props => {
              return (
                <div style="text-align:center">
                  <multiuse-button type="text" onClick={() => this.delsFunXj(props.row)}>
                    删除
                  </multiuse-button>
                </div>
              );
            }
          },
          { title: '配件代码', dataIndex: 'partCode', sorter: true,width: 120, },
          { title: '配件名称', dataIndex: 'partName', sorter: true },
          { title: '单位', dataIndex: 'partUnit', sorter: true,width: 60, },
          // { title: '单位', dataIndex: 'unitStr', sorter: true },
          { title: '数量', dataIndex: 'partCount', sorter: true,editType: 'number', editable: true, editRequired: true,width: 120,
            editValidator:(val, row, callback) => {
              if (row.partCount <0) {
                this.$notify.error({ title: '提示信息', message: '数量不能小于0' || '操作失败!' });
                row.partCount = 1
              }
            }
          },
          {
            title: '收件人',
            dataIndex: 'receiver',
            minWidth: 120,
            sorter: true,
            editable: true,
            editRequired: true,
            rules: [{required: true, message: '请输入收件人', trigger: 'blur'}],
            editType: 'input',
            render: props => {
              return <el-input v-model={props.row.receiver}>
                <el-button  slot="append"  icon="el-icon-search"
                            onClick={() => this.openDescDialog(props.row)}>
                </el-button>
              </el-input>;
            }
          },
          {
            title: '收件人电话',
            dataIndex: 'receiverTel',
            minWidth: 90,
            sorter: true,
            editable: true,
            editRequired: true,
            rules: [{required: true, message: '请输入收件人电话', trigger: 'blur'}],
            editType: 'input'
          }, {
            title: '收件地址',
            dataIndex: 'receiverAddress',
            minWidth: 90,
            sorter: true,
            editable: true,
            editRequired: true,
            rules: [{required: true, message: '请输入收件地址', trigger: 'blur'}],
            editType: 'input'
          },

        ];
      },
      createFormList2() {
        return [
          {
            type: 'INPUT',
            label: '返件要求说明',
            fieldName: 'urgentRemarks',
            selfCols: 3,// 元素占据几行
            rows: 2
          }
        ];
      },
    }
  };
</script>

<style lang="less" scoped></style>
